//
//  MYStockAlertViewController.m
//  HZTC_YaDeArt
//
//  Created by MayerF on 17/4/17.
//  Copyright © 2017年 HZTC. All rights reserved.
//

#import "MYStockAlertViewController.h"
#import "NSString+NormalTool.h"

@implementation MYStockAlertModel
@end

@interface MYStockAlertTableViewCell()<UITextFieldDelegate>
@property (nonatomic, strong)UILabel *pLeft;
@property (nonatomic, strong)UILabel *pRight;
@property (nonatomic, strong)UITextField *pTextField;
@property (nonatomic, strong)UILabel *pUnit;
@property (nonatomic, strong)MYStockAlertModel *pAletModel;
@property (nonatomic, copy)void(^ChangedAction)();
@end

@implementation MYStockAlertTableViewCell

+ (MYStockAlertTableViewCell *)cellTableView:(UITableView *)tableView
                                   indexPath:(NSIndexPath *)indexPath
                                   cellModel:(MYStockAlertModel *)cellModel
{
    static NSString *ID = @"stockCell";
    MYStockAlertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[MYStockAlertTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        [cell p_commonInit];
    }
    [cell p_updateDataWithmodel:cellModel indexPath:indexPath];
    cell.pAletModel = cellModel;
    
    return cell;
}

- (void)p_commonInit
{
    _pLeft = [UILabel new];
    _pRight = [UILabel new];
    _pTextField = [UITextField new];
    _pUnit = [UILabel new];
    
    _pLeft.font = _pRight.font = _pUnit.font = [UIFont systemFontOfSize:15];
    _pTextField.font = [UIFont systemFontOfSize:15];
    _pTextField.layer.borderWidth = 0.5;
    _pTextField.layer.borderColor = kMYHexToRGB(0xc8c7cc, 1).CGColor;
    _pTextField.delegate = self;
    _pRight.textAlignment = NSTextAlignmentLeft;
    _pTextField.textAlignment = NSTextAlignmentCenter;
    _pTextField.keyboardType = UIKeyboardTypeDecimalPad;
    
    [self.contentView addSubview:_pLeft];
    [self.contentView addSubview:_pRight];
    [self.contentView addSubview:_pTextField];
    [self.contentView addSubview:_pUnit];
    
    [self p_initConstraints];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)p_initConstraints
{
    CGFloat fPadding = 50;
    CGFloat fUnitW = 20;
    [_pLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self).offset(fPadding);
        make.right.mas_equalTo(_pRight.mas_left).offset(- 20);
        make.bottom.mas_equalTo(self);
        make.width.mas_equalTo(_pRight).multipliedBy(0.5);
    }];
    [_pRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.right.mas_equalTo(self).offset(-fPadding);
        make.bottom.mas_equalTo(self);
    }];
    [_pTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).offset(5);
        make.left.mas_equalTo(_pLeft.mas_right);
        make.right.mas_equalTo(_pUnit.mas_left).offset(-5);
        make.bottom.mas_equalTo(self).offset(-5);
    }];
    [_pUnit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.right.mas_equalTo(self).offset(-fPadding);
        make.bottom.mas_equalTo(self);
        make.width.mas_equalTo(fUnitW);
    }];
    
}

- (void)p_updateDataWithmodel:(MYStockAlertModel *)model indexPath:(NSIndexPath *)indexPath
{
    [self p_cleaOldData];
    [self p_updateNewData:model];
}

- (void)p_updateNewData:(MYStockAlertModel *)model
{
    _pLeft.text = model.model_left;
    _pRight.text = model.model_right;
    _pTextField.placeholder = model.model_placeHodler;
    _pUnit.text = model.model_unit;
    
    if (model.model_isShowTextField) {
        _pRight.hidden = YES;
        _pTextField.hidden = _pUnit.hidden = NO;
    }else {
        _pTextField.hidden = _pUnit.hidden = YES;
        _pRight.hidden = NO;
    }
}

- (void)p_cleaOldData
{
    [_pLeft setText:@""];
    [_pRight setText:@""];
    [_pUnit setText:@""];
}

- (void)p_refreshModel:(MYStockAlertModel *)model
{
    _pLeft.text = model.model_left;
    _pRight.text = model.model_right;
    _pTextField.placeholder = model.model_placeHodler;
    _pUnit.text = model.model_unit;
}

- (void)dealloc{
    DLog(@"MYStockAlertTableViewCell==dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -
#pragma mark notification
- (void)textFieldChange:(NSNotification *)noti
{
    UITextField *textField = noti.object;
    if ([_pTextField isEqual:textField]) {
        if (_pAletModel.model_isShowTextField) {
            _pAletModel.model_right = textField.text;
        }
        if (_ChangedAction) {
            _ChangedAction();
        }
    }
}
#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

@end

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

@interface MYStockAletView()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UILabel *pTitle;
@property (nonatomic, strong)UIScrollView *pScollView;
@property (nonatomic, strong)UIView *pContentSizeView;
@property (nonatomic, strong)UITableView *pTableView;
@property (nonatomic, strong)UILabel *pMessage;
@property (nonatomic, strong)UIButton *pCancel;
@property (nonatomic, strong)UIButton *pOK;
@property (nonatomic, strong)NSArray *pListData;
@property (nonatomic, copy)void(^CancelAction)(id result);
@property (nonatomic, copy)void(^OkAction)(id result);
@property (nonatomic, copy)void(^ChangedAction)(NSInteger row, id result);
@end

#define kTitleH 40
#define kCellH 35

@implementation MYStockAletView

#pragma mark -
#pragma mark lifeCycle
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self p_commonInit];
        self.backgroundColor = kMYHexToRGB(0xc8c7cc, 1);
    }
    return self;
}

- (void)dealloc{
    DLog(@"MYStockAletView==dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -
#pragma mark public
- (void)alertViewWithTitle:(NSString *)title
                   message:(NSString *)message
                      data:(NSArray<MYStockAlertModel *> *)data

{
    _pTitle.text = title;
    _pMessage.text = message;
    _pListData = data;
    [_pTableView reloadData];
    
    [self p_updateConstraints];
}

- (void)updateNewData:(NSArray<MYStockAlertModel *> *)data
{
    _pListData = data;
    [_pTableView reloadData];
}

- (void)refreshCellWithIndex:(NSInteger)index
{
    MYStockAlertTableViewCell *cell = [_pTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell p_refreshModel:_pListData[index]];
}
#pragma mark -
#pragma mark private
- (void)p_commonInit
{
    _pTitle = [UILabel new];
    _pScollView = [UIScrollView new];
    _pContentSizeView = [UIView new];
    _pMessage = [UILabel new];
    _pCancel = [UIButton new];
    _pOK = [UIButton new];
    _pTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _pTableView.delegate = self;
    _pTableView.dataSource = self;
    _pTableView.tableFooterView = [UIView new];
    _pTableView.bounces = NO;
    _pTableView.scrollEnabled = NO;
    
    self.layer.cornerRadius = 15;
    self.layer.masksToBounds = YES;
    _pScollView.backgroundColor = [UIColor whiteColor];
    _pTitle.textAlignment = NSTextAlignmentCenter;
    _pTitle.textColor = kMYHexToRGB(0xf15059, 1);
    _pTitle.backgroundColor = [UIColor whiteColor];
    _pMessage.font = [UIFont systemFontOfSize:11];
    _pMessage.textColor = kMYHexToRGB(0xf15059, 1);
    _pMessage.backgroundColor = [UIColor whiteColor];
    _pCancel.tag = 0;
    _pOK.tag = 1;
    _pCancel.backgroundColor = _pOK.backgroundColor = [UIColor whiteColor];
    [_pCancel setTitle:@"关闭" forState:UIControlStateNormal];
    [_pCancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_pCancel addTarget:self action:@selector(actionOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pOK setTitle:@"确认" forState:UIControlStateNormal];
    [_pOK setTitleColor:kMYHexToRGB(0xf15059, 1) forState:UIControlStateNormal];
    [_pOK addTarget:self action:@selector(actionOnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:_pTitle];
    [self addSubview:_pCancel];
    [self addSubview:_pOK];
    [self addSubview:_pScollView];
    [_pScollView addSubview:_pContentSizeView];
    [_pContentSizeView addSubview:_pTableView];
    [_pContentSizeView addSubview:_pMessage];
    
    [self p_initConstraints];
    
    [self p_registerNotification];
}

- (void)p_initConstraints
{
    [_pTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.height.mas_equalTo(kTitleH);
    }];
    [_pScollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pTitle.mas_bottom).offset(0.5);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.bottom.mas_equalTo(_pCancel.mas_top).offset(-0.5);
    }];
    [_pContentSizeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_pScollView);
        make.width.mas_equalTo(self);
        make.bottom.mas_equalTo(_pMessage.mas_bottom);
    }];
    [_pTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pContentSizeView).offset(10);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.height.mas_equalTo(0);
    }];
    [_pMessage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pTableView.mas_bottom).offset(10);
        make.left.mas_equalTo(self).offset(30);
        make.right.mas_equalTo(self).offset(-30);
    }];
    [_pCancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pScollView.mas_bottom).offset(0.5);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(_pOK.mas_left).offset(-0.5);
        make.width.mas_equalTo(_pOK);
        make.height.mas_equalTo(kTitleH);
        make.bottom.mas_equalTo(self);
    }];
    [_pOK mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pCancel);
        make.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
        make.height.mas_equalTo(kTitleH);
    }];
}

- (void)p_updateConstraints
{
    //分横竖屏
    CGFloat fUpDownMargin = 150;//竖屏,否则为30
    CGFloat fScrollViewH = kScreenH - fUpDownMargin*2 - kTitleH*2 - 0.5*2;
    CGFloat fMessageH = 0;
    CGFloat fContainterH = _pListData.count * kCellH + 10 + 10 + fMessageH;
    if (_pMessage.text && ![_pMessage.text isEqualToString:@""]) {
        fMessageH = [_pTitle.text heightWithLimitedWidth:CGRectGetWidth(self.frame) - 2*30 withFont:[UIFont systemFontOfSize:13]];
        fContainterH += fMessageH + 10;
    }
    
    if (fContainterH > fScrollViewH) {
        [_pScollView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(fScrollViewH);
        }];
        [_pTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(_pListData.count * kCellH);
        }];
        [_pMessage mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(fMessageH);
        }];
    }else {
        [_pScollView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(fContainterH);
        }];
        [_pTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(_pListData.count * kCellH);
        }];
        [_pMessage mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(fMessageH);
        }];
    }
    
}

- (void)addCancelAction:(void (^)(id result))cancelAction{
    _CancelAction = cancelAction;
}

- (void)addOkAction:(void (^)(id result))oKAction{
    _OkAction = oKAction;
}

- (void)addTextFieldDidChangedAction:(void(^)(NSInteger row, id result))changedAction
{
    _ChangedAction = changedAction;
}
#pragma mark -
#pragma mark notification
- (void)p_registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -
#pragma mark action
- (void)keyboardChange:(NSNotification *)noti
{
    NSDictionary* keyboardInfo = [noti userInfo];
    CGRect keyboardFrame = [keyboardInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    double animationDuration = [keyboardInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    if(noti.name == UIKeyboardWillShowNotification) {
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.superview).offset(-CGRectGetHeight(keyboardFrame)/2);
        }];
    }else if (noti.name == UIKeyboardWillHideNotification) {
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.superview);
        }];
    }
    [UIView animateWithDuration:animationDuration animations:^{
        [self.superview layoutIfNeeded];
    }];
}

- (void)actionOnClick:(UIButton *)btn
{
    NSMutableArray *tempArray = [NSMutableArray array];
    for (MYStockAlertModel *model in _pListData) {
        if (!model.model_right) {
            [tempArray addObject:@""];
        }else {
            [tempArray addObject:model.model_right];
        }
    }
    if (btn.tag == 0) {
        if (_CancelAction) {
            _CancelAction(tempArray);
        }
    }
    if (btn.tag == 1) {
        if (_OkAction) {
            _OkAction(tempArray);
        }
    }
    
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _pListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    MYStockAlertModel *mode = _pListData[indexPath.row];
    MYStockAlertTableViewCell *cell = [MYStockAlertTableViewCell cellTableView:tableView indexPath:indexPath cellModel:mode];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak typeof (self)weakSelf = self;
    cell.ChangedAction = ^(){
        if (weakSelf.ChangedAction) {
            weakSelf.ChangedAction(indexPath.row, mode);
        }
    };
    return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kCellH;
}

@end

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

@interface MYStockAlertViewController ()
@property (nonatomic, copy)NSString *pTitle;
@property (nonatomic, copy)NSString *pMessage;
@property (nonatomic, strong)NSArray *pData;
@property (nonatomic, strong)MYStockAletView *pStockAlertView;
@property (nonatomic, copy)void(^CancelAction)(id result);
@property (nonatomic, copy)void(^OkAction)(id result);
@property (nonatomic, copy)void(^ChangedAction)(NSInteger row, id result);
@end

@implementation MYStockAlertViewController

#pragma mark -
#pragma mark init
- (instancetype)init
{
    if (self = [super init]) {
        [self p_configureController];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        [self p_configureController];
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self p_configureController];
    }
    return self;
}
#pragma mark -
#pragma mark liftCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kMYHexToRGB(0x000000, 0.5);
    
    _pStockAlertView = [MYStockAletView new];
    
    [self.view addSubview:_pStockAlertView];
    [self p_initConstraints];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    __weak typeof (self)weakSelf = self;
    [_pStockAlertView addCancelAction:^(id result) {
        if (weakSelf.CancelAction) {
            weakSelf.CancelAction(result);
        }
        [weakSelf dismissViewControllerAnimated:NO completion:nil];
    }];
    [_pStockAlertView addOkAction:^(id result) {
        if (weakSelf.OkAction) {
            weakSelf.OkAction(result);
        }
    }];
    [_pStockAlertView addTextFieldDidChangedAction:_ChangedAction];
    
    [_pStockAlertView alertViewWithTitle:_pTitle message:_pMessage data:_pData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)dealloc{
    DLog(@"MYStockAlertViewController==dealloc");
}
#pragma mark -
#pragma mark public
+ (instancetype)alertControllerWithTitle:(NSString *)title
                                 message:(NSString *)message
                                    data:(NSArray<MYStockAlertModel *> *)data
{
    MYStockAlertViewController *alertVC = [self new];
    alertVC.pTitle = title;
    alertVC.pMessage = message;
    alertVC.pData = data;
    
    return alertVC;
}

- (void)updateNewData:(NSArray<MYStockAlertModel *> *)data
{
    [_pStockAlertView updateNewData:data];
}

- (void)refreshCellWithIndex:(NSInteger)index
{
    [_pStockAlertView refreshCellWithIndex:index];
}

- (void)addCancelAction:(void (^)(id))cancelAction{
    _CancelAction = cancelAction;
}

- (void)addOkAction:(void (^)(id))oKAction{
    _OkAction = oKAction;
}

- (void)addTextFieldDidChangedAction:(void(^)(NSInteger row, id result))changedAction
{
    _ChangedAction = changedAction;
}
#pragma mark -
#pragma mark private
- (void)p_configureController
{
//    self.providesPresentationContextTransitionStyle = YES;
//    self.definesPresentationContext = YES;
    self.modalPresentationStyle = UIModalPresentationCustom;
//    self.transitioningDelegate = self;
}

- (void)p_initConstraints
{
    [_pStockAlertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
    }];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

@end
